<?php
namespace Admin\Api;

use Admin\Common\Controller;
use Portal\Domain\Admin as AdminDomain;

/**
 * 
 */
class Admin extends Controller {
    
    /**
     * 修改密码
     * @desc 修改管理员自己的密码
     */
    public function alterPassword() {
        $domain = new AdminDomain();

        $isAlter = false;
        $error = null;
        if ($_POST) {
            $oldPassword = $this->request->get('oldPassword');
            $newPassword = $this->request->get('newPassword');
            $newPassword2 = $this->request->get('newPassword2');

            if ($newPassword != $newPassword2) {
                $error = '确认密码不一致，请重新输入';
            } else if ($oldPassword && $newPassword) {
                include API_ROOT . '/public/oauth/server.php';
                if ($storage->checkUserCredentials(\PhalApi\DI()->admin->username, $oldPassword)) {
                    $storage->setUser(\PhalApi\DI()->admin->username, $newPassword); // HACK 密码修改，以及原来的信息保留
                    $isAlter = true;
                    $error = '密码修改成功，请重新登录';
                } else {
                    $error = '旧密码错误';
                }
                //$isAlter = $domain->alterPassword($oldPassword, $newPassword);
                //$error = $isAlter ? '密码修改成功，请重新登录' : '旧密码错误';
            } else {
                $error = '请输入密码';
            }
        }

        return $this->render('admin/alterPassword.html', ['isAlter' => $isAlter, 'error' => $error, 'oldPassword' => $oldPassword, 'newPassword' => $newPassword, 'newPassword2' => $newPassword2]);
    }

    /**
     * 操作权限
     * @desc 查看管理后台操作权限
     */
    public function checkRights() {
        $rights = [];
        $username = \PhalApi\DI()->admin->username;
        $iadminosRights = \PhalApi\DI()->iadminosRights;

        $adminDocs = $this->getApiInfo();

        $csvFile = API_ROOT . '/plugins/iadminos_rights_rbac_policy.csv';
        $row = 1;
        if (($handle = fopen($csvFile, "r")) !== FALSE) {
            while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                if (empty($data) || $data[0] != 'p') {
                    continue;
                }

                $object = trim($data[2]);
                $action = trim($data[3]);
                $title = isset($adminDocs['Admin.'.$object.'.'.$action]) ? $adminDocs['Admin.'.$object.'.'.$action]['title'] : '';

                $item = ['id' => $row, 'url' => '/'.$object. '/' . $action, 'title' => $title, 'desc' => '', 'is_assign' => $iadminosRights->checkLite($username, $object, $action)];
                $row ++;

                $rights[] = $item;
            }
            fclose($handle);
        }

        $data = ['rights' => $rights];

        return $this->render('admin/checkRights.html', $data);
    }

    public function manageRights() {
        $csvFile = API_ROOT . '/plugins/iadminos_rights_rbac_policy.csv';
        $rights = file_get_contents($csvFile);

        $error = null;
        if (!empty($_POST['rights'])) {
            $rights = $_POST['rights'];
            if (is_writeable($csvFile)) {
                file_put_contents($csvFile, $rights);
            } else {
                $error = '缺少文件写入权限：plugins/iadminos_rights_rbac_policy.csv';
            }
        }

        $data = ['rights' => $rights, 'error' => $error];

        return $this->render('admin/manageRights.html', $data);
    }

    protected function getApiInfo(){
        $_GET['namespace'] = 'Admin';

        ob_start();
        $apiList = new \PhalApi\Helper\ApiList('');
        $tpl = API_ROOT . '/src/view/docs/api_list_tpl_ajax.php';
        $apiList->render($tpl);
        $apisJsonStr = ob_get_contents();
        ob_end_clean();
        $arr = json_decode($apisJsonStr, true);

        $rs = array();
        foreach ($arr['apis'] as $it) {
            foreach ($it['items'] as $it2) {
                $rs[$it2['service']] = ['title' => $it2['title']];
            }
        }
        return $rs;
    }
}

